/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.agent.execute;

import cn.ac.iie.agent.controller.Controller;
import cn.ac.iie.agent.service.FtpDownloadService;
import cn.ac.iie.agent.service.FtpUploadService;
import cn.ac.iie.agent.service.HdfsUploadService;
import cn.ac.iie.agent.service.XmlService;

import cn.ac.iie.agent.tools.FileTools;
import cn.ac.iie.agent.tools.XmlTools;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

public class AgentDataCollectHandler implements HandlerI {

    private static Logger logger = Logger.getLogger(AgentDataCollectHandler.class);
    public static String modelPath = ClassLoader.getSystemClassLoader().getResource("agent_rs_model.xml").getFile();

    /**
     *
     * @param pRequestContent
     * @return
     */
    public String execute(Request pRequest) {

        String pRequestContent = "";
        try {
            pRequestContent = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        logger.info("xml:" + pRequestContent);
        String xml = pRequestContent;
        String rs = "";//最终要返回的xml
        long parseBeginTime = System.currentTimeMillis();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //获取返回xml模板
        boolean paraFlag = true;
        FileTools fileTools = new FileTools();
        String rq_xml = fileTools.readFile(modelPath);
        //解析xml 
        Map<String, String> rsMap = new HashMap<String, String>();//存放返回xml时用得参数及值,key是xml的标签，value是值
        logger.info("begin check xml");
        paraFlag = new XmlService().check(xml, rsMap);

        String subjobid = XmlTools.getElValueFromStr(xml, "subjobid");
        String instance = XmlTools.getElementAttributeValue(xml, "operator", "name");
        String operatorname = XmlTools.getElementAttributeValue(xml, "operator", "class");
        rsMap.put("subjobid", subjobid);
        rsMap.put("instance", instance);
        rsMap.put("operatorname", operatorname);
        if (!paraFlag) {
            logger.info(subjobid + " para is error!");
            try {
                rs = XmlTools.replace(rq_xml, rsMap);
                logger.info(subjobid + " rs:" + rs);
            } catch (Exception ex) {
                logger.info(subjobid + " rs replace error!", ex);
            }

            return rs;
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////

        String hdfsPath = XmlTools.getElValueFromStr(xml, "hdfsPathOne");
        String type = XmlTools.getValueFromStrDGText(xml, "type");
        String name = XmlTools.getValueFromStrDGText(xml, "name");
        String agentIP = XmlTools.getElValueFromStr(xml, "agentIPOne");
        //填充agentIP
        rsMap.put("agentIP", agentIP);

        //判断该系统是否正在采集
        Iterator<String> itr6 = Controller.subThreadList.iterator();
        while (itr6.hasNext()) {
            logger.debug("exist task:" + itr6.next().toString());
        }

        boolean existFlag = false;
        Iterator<String> itr1 = Controller.subThreadList.iterator();
        while (itr1.hasNext()) {
            if (itr1.next().equals(name)) {
                existFlag = true;
                break;
            }
        }
        if (existFlag) {
            logger.info(subjobid + " " + name + " has already exist!");
            try {
                rsMap.put("status", "fail");
                rsMap.put("desc", name + " already exist!");
                rs = XmlTools.replace(rq_xml, rsMap);
                logger.info(subjobid + " rs:" + rs);
            } catch (Exception ex) {
                logger.info(subjobid + " rs replace error!", ex);
            }
            return rs;
        } else {
            logger.info(subjobid + " add:" + name);
            Controller.subThreadList.add(name);
        }
        //采集
        if (type.equals("local")) {
            logger.info(subjobid + " local begin");
            String fileType = XmlTools.getValueFromStrDGText(xml, "fileType");
            String timeout = XmlTools.getValueFromStrDGText(xml, "timeout");
            String localFilePath = XmlTools.getValueFromStrDGText(xml, "localFilePath");
            new HdfsUploadService().upload(localFilePath, fileType, subjobid, hdfsPath, name, timeout, rsMap);
            logger.info(subjobid + " local end");
        } else if (type.equals("ftpdownload")) {
            //企业侧--平台侧
            logger.info(subjobid + " ftpdownload begin");
            rsMap = new FtpDownloadService().execute(xml, rsMap, subjobid);
            logger.info(subjobid + " ftpdownload finish");
        } else if (type.equals("ftpupload")) {
            //平台侧--企业侧
            logger.info(subjobid + " ftpupload begin");
            rsMap = new FtpUploadService().execute(xml, rsMap, subjobid);
            logger.info(subjobid + " ftpupload finish");
        }

        //填充runtime
        long parseEndTime = System.currentTimeMillis();
        Long runtime = (parseEndTime - parseBeginTime) / 1000;
        rsMap.put("time", runtime.toString());
        logger.info(subjobid + " name: " + name + " agent run time is " + runtime.toString());
        //返回结果信息
        try {
            rs = XmlTools.replace(rq_xml, rsMap);
            logger.info(subjobid + " rs: " + rs);
        } catch (Exception ex) {
            logger.info(subjobid + " rs replace error!", ex);
        }
        //执行结束，从链表中删除
        Iterator<String> itr2 = Controller.subThreadList.iterator();
        while (itr2.hasNext()) {
            if (itr2.next().equals(name)) {
                itr2.remove();
                logger.info(subjobid + " name: " + name + " remove!");
                break;
            }
        }
        return rs;
    }
}
